package cn.baddonkey.photography.agent.core.exception;

import cn.baddonkey.photography.agent.core.APIResponseStatus;
import cn.baddonkey.photography.agent.core.PlatformResponse;

import jakarta.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public PlatformResponse onMethodArgumentNotValid(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.getFieldError() == null) {
            log.error("参数错误");
            return PlatformResponse.error(APIResponseStatus.U9999, "参数错误");
        } else {
            log.error(bindingResult.getFieldError().getDefaultMessage());
            return PlatformResponse.error(
                    APIResponseStatus.U9999, bindingResult.getFieldError().getDefaultMessage());
        }
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public PlatformResponse handlerAppServicesRuntimeException(
            HttpServletRequest request, Exception ex) {
        log.error(ex.getMessage(), ex);
        return PlatformResponse.error(APIResponseStatus.U9999, ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public PlatformResponse handlerAppServicesException(HttpServletRequest request, Exception ex) {
        log.error(ex.getMessage(), ex);
        return PlatformResponse.error(APIResponseStatus.U9999, "系统异常");
    }
}
